
var cid,menuName;
var table = layui.table;

var functionList;
$(document).ready(function () {
    menuName = $.trim($(".page-tabs-content",window.parent.document).children(".active").text());
    cid = $(".page-tabs-content",window.parent.document).children(".active").data("cid");
    $("#ibox-title").text(menuName+'管理');
    $("input[name='menuId']").val(cid);
    CKEDITOR.replace('articleIntro');
    CKEDITOR.replace('articleKeyQuestion');
    CKEDITOR.replace('articleKeyTech');
    CKEDITOR.replace('articleResponsor');
    CKEDITOR.replace('articleUnit');
    CKEDITOR.replace('articleContent');
    renderTable();
});
layui.use('laydate', function(){
    laydate = layui.laydate;
    //执行一个laydate实例
    laydate.render({
        type:"datetime",
        elem: '#articleUpdatetime' //指定元素
    });
});
function renderTable(){
    //执行渲染
    table.render({
        even:true//隔行背景
        ,elem: '#article-list' //指定原始表格元素选择器（推荐id选择器）
        ,height: 'full-220' //容器高度
        ,cols: [[{checkbox: true}
            ,{field: 'articleId', title: 'ID',sort:false,width:100}
            ,{field: 'articleTitle', title: '文章标题',sort:true,width:400}
            ,{field: 'articleFile', title: '文章简介',sort:true,width:400}
            ,{field: 'articleAuthor', title: '作者',sort:true,width:100}
            ,{field: 'articleUpdatetime', title: '更新时间',sort:true,width:100,templet:'<div>{{(new Date(d.articleUpdatetime)).toLocaleDateString()}}</div>'}
            ,{field: 'articleOrder', title: '文章排序',sort:true,width:100}
            ,{field: 'articleIsHome', title: '是否推荐到首页',sort:true,width:140,templet:'#recHomeTpl'}
            ,{fixed: 'right', width:200, align:'center', toolbar: '#toolBar',title:'操作'} //这里的toolbar值是模板元素的选择器

        ]] //设置表头
        ,url: '/manage/article/getArticles/'+cid
        ,where: {
            keywords:$("#keyword").val(),
            field:'articleOrder',
            order:'DESC'
        }
        ,method: 'post' //如果无需自定义HTTP类型，可不加该参数
        //request: {} //如果无需自定义请求参数，可不加该参数
        ,response: {
            statusName: 'status' //数据状态的字段名称，默认：code
            ,statusCode: 1 //成功的状态码，默认：0
            ,dataName: 'result' //数据列表的字段名称，默认：data
        } //如果无需自定义数据响应名称，可不加该参数
        ,page:true
        ,limits:[10,20,30,40,50,60,70,80,90,100]
        ,limit:10
        ,loading:true
        ,id:'id'
        //,…… //更多参数参考右侧目录：基本参数选项
    });
    //监听工具条
    table.on('tool(test)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值
        var tr = obj.tr; //获得当前行 tr 的DOM对象

        if(layEvent === 'del'){ //删除
            deleteArticles(obj);
        } else if(layEvent === 'edit'){ //编辑
            openEditArticle(obj);
        }
    });
    table.on('sort(test)', function(obj){ //注：sort是排序事件名，test是table原始容器的属性 lay-filter="对应的值"
        console.log(obj.field); //当前排序的字段名
        console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
        console.log(this); //当前排序的 th 对象

        //尽管我们的 table 自带排序功能，但并没有请求服务端。
        //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，如：
        table.reload('id', {
            initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
            ,where: { //请求参数
                field: obj.field //排序字段
                ,order: obj.type //排序方式
            }
        });
    });
}
//重新加载数据
function reloadTableData(){
    table.reload('id',{
        method:'post'
        ,url: '/manage/article/getArticles/'+cid
        ,where: {
            keywords:$("#keyword").val(),
            field:'articleOrder',
            order:'DESC'
        }
    });
}
var form;
layui.use(['form'], function(){
    form = layui.form;
    //自定义验证规则
    form.verify({
        title: function(value){
            if(value.length < 2){
                return '标题至少得2个字符啊';
            }
        }
    });

    //监听提交
    form.on('submit(demo1)', function(data){
        var url = "/manage/article/updateArticle";
        data.field.articleIntro = CKEDITOR.instances.articleIntro.getData();
        data.field.articleKeyQuestion = CKEDITOR.instances.articleKeyQuestion.getData();
        data.field.articleKeyTech = CKEDITOR.instances.articleKeyTech.getData();
        data.field.articleResponsor = CKEDITOR.instances.articleResponsor.getData();
        data.field.articleUnit = CKEDITOR.instances.articleUnit.getData();
        data.field.articleContent = CKEDITOR.instances.articleContent.getData();
        if(typeof(data.field.articleIsHome)=="undefined"){
            data.field.articleIsHome="0";
        }
        if(typeof(data.field.articleIsHomePicture)=="undefined"){
            data.field.articleIsHomePicture="0";
        }
        if(typeof(data.field.articleIsHomeFirst)=="undefined"){
            data.field.articleIsHomeFirst="0";
        }
        if(typeof(data.field.articleIsHomeNews)=="undefined"){
            data.field.articleIsHomeNews="0";
        }
        if(typeof(data.field.articleIsHomeKeyProject)=="undefined"){
            data.field.articleIsHomeKeyProject="0";
        }
        displayLoading(true);
        $.post(url,data.field,
            function(data){
                if(data.status==1){
                    layer.msg('保存成功', {icon: 6});
                    $("#user-model").modal('hide');
                    reloadTableData();
                }
                else if(data.status==4){
                    window.location.href="/manage/nopermission.html";
                }
                else if(data.status==5){
                    layer.confirm(data.msg, {icon: 3, title:'提示'}, function(index){
                        window.location.href="/manage/login.html";
                        layer.close(index);
                    });
                }
                else{
                    layer.msg(data.msg, {icon: 6});
                }
                hiddenLoading(true);
            });
        return false;
    });
});
function openAddArticle(){
    $("#edit-title").text('新增'+menuName);
    $(":reset").click();//重置所有表单元素
    $("input[name='articleId']").val(0);
    $('#articleOrder').val(0);//默认排后面
    $('#articlePicture').val('');
    $('#articlePicture2').val('');
    var now = new Date();
    strNow  = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+now.getDate()+" "+ now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
    $('#articleUpdatetime').val(strNow);//默认排后面
    $("#user-model").modal({
        keyboard: true
    });
    CKEDITOR.instances.articleIntro.setData($('#articleIntro').val());
    CKEDITOR.instances.articleKeyQuestion.setData($('#articleKeyQuestion').val());
    CKEDITOR.instances.articleKeyTech.setData($('#articleKeyTech').val());
    CKEDITOR.instances.articleResponsor.setData($('#articleResponsor').val());
    CKEDITOR.instances.articleUnit.setData($('#articleUnit').val());
    CKEDITOR.instances.articleContent.setData($('#articleContent').val());
}
function openEditArticle(obj){
    $("#edit-title").text('编辑'+menuName);
    displayLoading(true);
    $.post('/manage/article/getArticle',{articleId:obj.data.articleId},
        function(data){
            if(data.status==1){
                $(":reset").click();//重置所有表单元素
                $("input[name='articleId']").val(data.result.articleId);
                $('#articleTitle').val(data.result.articleTitle);
                $('#articleSource').val(data.result.articleSource);
                $('#articleAuthor').val(data.result.articleAuthor);
                $('#articleFile').val(data.result.articleFile);
                $('#articlePicture').val(data.result.articlePicture);
                $('#articlePicture2').val(data.result.articlePicture2);
                $('#articleOrder').val(data.result.articleOrder);
                var now = new Date(data.result.articleUpdatetime);
                strNow  = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+now.getDate()+" "+ now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
                $('#articleUpdatetime').val(strNow);
                if(data.result.articleIsHome){
                    $('#articleIsHome').next().click();
                }
                if(data.result.articleIsHomePicture){
                    $('#articleIsHomePicture').next().click();
                }
                if(data.result.articleIsHomeFirst){
                    $('#articleIsHomeFirst').next().click();
                }
                if(data.result.articleIsHomeNews){
                    $('#articleIsHomeNews').next().click();
                }
                if(data.result.articleIsHomeKeyProject){
                    $('#articleIsHomeKeyProject').next().click();
                }
                $('#articleIntro').val(data.result.articleIntro);
                $('#articleKeyQuestion').val(data.result.articleKeyQuestion);
                $('#articleKeyTech').val(data.result.articleKeyTech);
                $('#articleResponsor').val(data.result.articleResponsor);
                $('#articleUnit').val(data.result.articleUnit);
                $('#articleContent').val(data.result.articleContent);
            }
            else if(data.status==4){
                window.location.href="/manage/nopermission.html";
            }
            else if(data.status==5){
                layer.confirm(data.msg, {icon: 3, title:'提示'}, function(index){
                    window.location.href="/manage/login.html";
                    layer.close(index);
                });
            }
            else{
                layer.msg(data.msg, {icon: 6});
            }
            CKEDITOR.instances.articleIntro.setData($('#articleIntro').val());
            CKEDITOR.instances.articleKeyQuestion.setData($('#articleKeyQuestion').val());
            CKEDITOR.instances.articleKeyTech.setData($('#articleKeyTech').val());
            CKEDITOR.instances.articleResponsor.setData($('#articleResponsor').val());
            CKEDITOR.instances.articleUnit.setData($('#articleUnit').val());
            CKEDITOR.instances.articleContent.setData($('#articleContent').val());
            hiddenLoading(true);
        });
    $("#user-model").modal({
        keyboard: true
    });
}
function deleteArticles(obj){
    layer.confirm('确认要删除此数据吗？', function(index){
        layer.close(index);
        var articleIdList = new Array();
        if(obj){//删除单行
            articleIdList.push(obj.data.articleId);
        }
        else{//删除选中行
            var checkStatus = table.checkStatus('id');
            if(checkStatus.data.length==0){
                layer.msg('请先选择要删除的行',{icon:5});
                return;
            }
            else{
                checkStatus.data.forEach(function(item,index,dataList){
                    articleIdList.push(item.articleId);
                });
            }
        }
        displayLoading(true);
        $.post("/manage/article/deleteArticles",{articleIdList:articleIdList},
            function(data){
                if(data.status==1){
                    //先更新本地数据
                    layer.msg('删除成功', {icon: 6});
                }
                else if(data.status==4){
                    window.location.href="/manage/nopermission.html";
                }
                else if(data.status==5){
                    layer.confirm(data.msg, {icon: 3, title:'提示'}, function(index){
                        window.location.href="/manage/login.html";
                        layer.close(index);
                    });
                }
                else{
                    layer.msg(data.msg, {icon: 6});
                }
                hiddenLoading(true);
                $("#user-model").modal('hide');
                reloadTableData();
            });
    });
}
layui.use('upload', function(){
    var upload = layui.upload;

    //上传图片
    var uploadPictrue = upload.render({
        accept:'images'
        ,size:1024
        ,exts:'jpg|jpeg|png|gif|bmp'
        ,elem: '#uploadPictrue' //绑定元素
        ,url: '/manage/uploadPicture' //上传接
        ,before: function(obj){
            layer.load(); //上传loading
        }
        ,done: function(res){
            if(res.status==1){
                $("#articlePicture").val(res.result);
                layer.msg('上传成功', {icon: 6});
            }
            else if(res.status==4){
                window.location.href="/manage/nopermission.html";
            }
            else if(res.status==5){
                layer.confirm(res.msg, {icon: 3, title:'提示'}, function(index){
                    window.location.href="/manage/login.html";
                    layer.close(index);
                });
            }
            else{
                layer.msg(res.msg, {shift: 6});
            }
            layer.closeAll('loading');
        }
        ,error: function(){
            //请求异常回调
            layer.msg('接口异常', {shift: 6});
            layer.closeAll('loading');
        }
    });//上传图片
    var uploadPictrue2 = upload.render({
        accept:'images'
        ,size:1024
        ,exts:'jpg|jpeg|png|gif|bmp'
        ,elem: '#uploadPictrue2' //绑定元素
        ,url: '/manage/uploadPicture' //上传接
        ,before: function(obj){
            layer.load(); //上传loading
        }
        ,done: function(res){
            if(res.status==1){
                $("#articlePicture2").val(res.result);
                layer.msg('上传成功', {icon: 6});
            }
            else if(res.status==4){
                window.location.href="/manage/nopermission.html";
            }
            else if(res.status==5){
                layer.confirm(res.msg, {icon: 3, title:'提示'}, function(index){
                    window.location.href="/manage/login.html";
                    layer.close(index);
                });
            }
            else{
                layer.msg(res.msg, {shift: 6});
            }
            layer.closeAll('loading');
        }
        ,error: function(){
            //请求异常回调
            layer.msg('接口异常', {shift: 6});
            layer.closeAll('loading');
        }
    });
    //上传文件
    var uploadFile = upload.render({
        accept:'file'
        ,size:1024*500
        ,exts:'doc|docx|pdf|rar|zip|txt|mp4|xls|xlsx|ppt|pptx'
        ,elem: '#uploadFile' //绑定元素
        ,url: '/manage/uploadFile' //上传接口接
        ,before: function(obj){
            layer.load(); //上传loading
        }
        ,done: function(res){
            if(res.status==1){
                $("#articleFile").val(res.result);
                layer.msg('上传成功', {icon: 6});
            }
            else if(res.status==4){
                window.location.href="/manage/nopermission.html";
            }
            else if(res.status==5){
                layer.confirm(res.msg, {icon: 3, title:'提示'}, function(index){
                    window.location.href="/manage/login.html";
                    layer.close(index);
                });
            }
            else{
                layer.msg(res.msg, {shift: 6});
            }
            layer.closeAll('loading');
        }
        ,error: function(){
            layer.msg('接口异常', {shift: 6});
            layer.closeAll('loading');
        }
    });
});
$("#addArticle").on('click',openAddArticle);
$("#refresh,#search").on("click",reloadTableData);
$("#delAll").on('click',function(){deleteArticles()});
$("#articlePicture,#articlePicture2").on("dblclick",function(){
    layer.open({
        title:'图片预览',
        type: 1,
        content: '<img src="'+$(this).val()+'" width="300" />' //这里content是一个普通的String
    });
});
$("#articleFile").on("dblclick",function(){
    window.open($(this).val());
});
$("#browseServer").on("click",function(){
    layer.open({
        title:'文件浏览器',
        area: ['80%', '80%'],
        type: 2,
        content: ['/manage/plugins/wxFile/browser.html?formName=articlePicture', 'no'] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content:
    });
});
$("#browseServer2").on("click",function(){
    layer.open({
        title:'文件浏览器',
        area: ['80%', '80%'],
        type: 2,
        content: ['/manage/plugins/wxFile/browser.html?formName=articlePicture2', 'no'] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content:
    });
});
$("#browseFileServer").on("click",function(){
    layer.open({
        title:'文件浏览器',
        area: ['80%', '80%'],
        type: 2,
        content: ['/manage/plugins/wxFile/browser.html?formName=articleFile', 'no'] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content:
    });
});